# -*- coding: utf-8 -*-
import pymysql
import re
#连接数据库
try:
    conn = pymysql.Connection(host="192.168.0.113",port=3306,user='coname',password='xZS6p4LDcKCwn4Yb',db="co",charset="utf8")
    cursor = conn.cursor()
    print('连接数据库成功!')
except Exception as e:
    print("连接数据库失败!>>>",e)
#获取水果数据源
try:
    cursor.execute('select content,srname from co_fruit ')#where srname ="苹果"
    resutls = cursor.fetchall()
except Exception as e:
    print('查询数据失败!>>>',e)
#获取清洗后的字段
try:
    for resutl in resutls:
        res1=resutl[1] 
        res0=resutl[0]
        if "分布范围编辑" in res0:
            pat="分布范围编辑(.*?)\["
        elif "分布范围" in res0:
            pat="分布范围[\u4e00-\u9fa5]{1,2}(.*?)。\["
        elif "分布区域编辑" in res0:
            pat="分布区域编辑(.*?)\["
        elif "分布区域" in res0:
            pat="分布区域[\u4e00-\u9fa5]{1,2}(.*?)\["
        elif "产地生境编辑" in res0:
            pat="产地生境编辑(.*?)\["
        elif "产地生境" in res0:
            pat="产地生境[\u4e00-\u9fa5]{1,2}(.*?)\["
        elif "地理分布编辑" in res0:
            pat="地理分布编辑(.*?)\["
        elif "地理分布" in res0:
            pat="地理分布[\u4e00-\u9fa5]{1,2}(.*?)\["
        elif "分布情况编辑" in res0:
            pat="分布情况编辑(.*?)\["
        elif "分布情况" in res0:
            pat="分布情况[\u4e00-\u9fa5]{1,2}(.*?)\["
        elif "产地分布编辑" in res0:
            pat="产地分布编辑(.*?)\["
        elif "产地分布" in res0:
            pat="产地分布[\u4e00-\u9fa5]{1,2}(.*?)\["
        elif "分类编辑" in res0:
            pat="分类编辑(.*?)\["
        elif "分类" in res0:
            pat="分类[\u4e00-\u9fa5]{1,2}(.*?)\["   
        else:
            print('更新<<<'+res1+'>>>来源失败')
            continue
        # print(res0)
        res0s = re.findall(pat, res0)
        if len(res0s)>0:
            res0 = res0s[0]
            cursor.execute('update co_fruit set srfrom ="{}" where srname="{}"'.format(res0,res1))
            conn.commit()
            print("更新<<<"+res1+">>>来源成功")
        else:
            continue
except Exception as e:
    print('更新数据失败!>>>',e)
#关闭数据库
try:
    cursor.close()
    conn.close()
    print('关闭数据库成功!')
except Exception as e:
    print('连接数据库失败>>>',e)